package com.tanhua.sso.controller;

import com.tanhua.sso.service.SmsService;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.Map;

@RestController
@RequestMapping("user")
@Slf4j
public class SmsController {
    @Autowired
    private SmsService smsService;

    /**
     * 发送短信验证码接口
     *
     * @param param
     * @return
     */
    @PostMapping("login")
    public ResponseEntity<ErrorResult> sendCheckCode(@RequestBody Map<String, String> param) {//从请求体中 拿到请求参数
        ErrorResult errorResult = null;
        //从请求参数中获取手机号
        String phone = param.get("phone");
        try {
            //调用service层 将手机号传递过去  得到验证码发送结果
            errorResult = this.smsService.sendCheckCode(phone);
            //如果返回结果为空 证明验证码发送成功 没有返回错误信息
            if (null == errorResult) {
                //return 200    响应结果为空
                return ResponseEntity.ok(null);
            }
        } catch (Exception e) {
            //如果验证码发送失败  记录日志
            log.error("发送验证码失败! phone = " + phone, e);
            //响应错误信息
        }
        errorResult = ErrorResult.builder().errCode("000002").errMessage("验证码发送失败!").build();
        // 返回验证结果
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }
}
